<template>
  <div style="overflow-x: hidden; overflow-y: auto; height: 95%">
    <!-- 已排区 -->
    <div id="alreadyOrdered2">
      <a-form ref="formRef2" size="small" :model="pageData" layout="inline" style="margin-left: 24px">
        <a-form-item label="车间">
          <a-select v-model="pageData.workshopId2" style="width: 120px" class="bacClass" allow-clear>
            <a-option :value="1">染部A</a-option>
            <a-option :value="2">染部B</a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="流转卡号">
          <a-input allow-clear style="width: 120px" class="bacClass" v-model="pageData.flowCardCode2" />
        </a-form-item>
        <a-form-item label="机台类型" field="machineTypeId2" :validate-trigger="['change', 'blur']"
          :rules="[{ required: true, message: '机台类型必填' }]">
          <a-select v-model="pageData.machineTypeId2" class="bacClass" @focus="machineTypeSearch"
            @change="machineSearch" allow-search allow-clear style="width: 120px">
            <a-option v-for="item in pageData.typeList" :value="item.id" :key="item.typeName">
              {{ item.typeName }}
            </a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="状态">
          <a-input allow-clear style="width: 120px" class="bacClass" v-model="pageData.flowCardCode2" />
        </a-form-item>
        <div style="display: flex">
          <a-button type="primary" style="margin-right: 28px" @click="doRefresh2('')">查询</a-button>
          <a-button type="outline" style="margin-right: 28px" @click="editOrder()">修改</a-button>
        </div>
      </a-form>
      <div class="divInterval"></div>
      <div class="divCenter">
        <a-button class="buttonLeft" type="primary">已<br />排<br />区</a-button>
        <a-spin :loading="pageData.pageLoading2" tip="加载中" dot style="width: 95%; z-index: 999">
          <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
            style="height: 400px; width: 100%" :suppressDragLeaveHidesColumns="true" rowSelection="multiple"
            @grid-ready="gridReady2" :defaultColDef="defaultColDef" class="ag-theme-alpine"
            :rowData="pageData.arrangedList" :columnDefs="tableColumns2" :localeText="localeText1"
            :rowDragManaged="true" :animateRows="true" @rowDragEnd="onRowDragEnd">
          </AgGridVuesCopys>
        </a-spin>
      </div>
    </div>
    <!-- 调转位置图标按钮 -->
    <div id="gang2">
      <icon-double-down @click="transferDown()" style="margin-left: 50%" :strokeWidth="3" :size="22" />
    </div>
    <!-- 未排区 -->
    <div id="notOrdered2">
      <a-form ref="formRef" size="small" :model="pageData" layout="inline" style="margin-left: 24px">
        <a-form-item label="流转卡号">
          <a-input allow-clear style="width: 120px" class="bacClass" v-model="pageData.flowCardCode" />
        </a-form-item>
        <a-form-item label="机台类型" field="machineTypeId" :validate-trigger="['change', 'blur']"
          :rules="[{ required: true, message: '机台类型必填' }]">
          <a-select v-model="pageData.machineTypeId" class="bacClass" @search="machineTypeSearch"
            @focus="machineTypeSearch" allow-search allow-clear style="width: 120px">
            <a-option v-for="item in pageData.typeList" :value="item.id" :key="item.typeName">
              {{ item.typeName }}
            </a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="流转状态">
          <a-input allow-clear style="width: 120px" class="bacClass" v-model="pageData.flowCardCode" />
        </a-form-item>
        <a-button type="primary" style="margin-right: 28px" @click="doRefresh()">查询</a-button>
        <a-form-item label="车间">
          <a-select v-model="pageData.workshopId" style="width: 120px" class="bacClass" allow-clear>
            <a-option :value="1">染部A</a-option>
            <a-option :value="2">染部B</a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="已排">
          <a-input style="width: 70px" class="bacClass" v-model="pageData.arrangedSum" disabled />
        </a-form-item>
        <a-form-item label="未排">
          <a-input style="width: 70px" class="bacClass" v-model="pageData.unscheduledSum" disabled />
        </a-form-item>
      </a-form>
      <div class="divInterval"></div>
      <div class="divCenter">
        <a-button class="buttonLeft" type="primary" style="margin-top: -10px; height: 250px">未<br />排<br />区</a-button>
        <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="width: 95%; z-index: 999; margin-bottom: 10px">
          <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
            style="height: 250px; width: 100%" :suppressDragLeaveHidesColumns="true" rowSelection="multiple"
            @grid-ready="gridReady" :defaultColDef="defaultColDef" class="ag-theme-alpine"
            :rowData="pageData.unscheduledList" :columnDefs="tableColumns" :localeText="localeText1">
          </AgGridVuesCopys>
        </a-spin>
      </div>
    </div>
    <!-- 机台 -->
    <div style="margin-left: 9px; width: 99%; margin-bottom: 20px">
      <div class="divMachine" v-for="(item, index) in pageData.machineList" :key="index"
        @click="machineQuery(index, item.code)" :style="{
        backgroundColor: item.backColor,
        boxShadow: item.shadowColor,
      }">
        {{ item.code }}
      </div>
    </div>
  </div>
  <!-- 排产弹窗 -->
  <a-drawer style="z-index: 999" ok-text="保存" cancel-text="关闭" :drawer-style="{ zIndex: 9999 }" :mask-closable="false"
    :visible="pageData.apsShow" :ok-loading="pageData.pageLoading" unmountOnClose placement="bottom" height="100%"
    @ok="apsOk" @cancel="pageData.apsShow = false">
    <template #title>
      {{ pageData.sideTitle }}
    </template>
    <div>
      <table class="table" v-if="pageData.sideTitle != '已排产顺序调整'">
        <thead>
          <tr>
            <th>排产卡号</th>
            <th>{{ dataForm.flowCardCode.split('_')[0] }}</th>
            <th>缸型</th>
            <th>{{ dataForm.cylinderType }}</th>
            <th>管型</th>
            <th>{{ dataForm.castNum }}</th>
            <th>匹数</th>
            <th>{{ dataForm.houseNum }}</th>
            <th>重量</th>
            <th>{{ dataForm.flowCardWeight }}</th>
          </tr>
        </thead>
      </table>
      <!-- 机台排产 -->
      <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
        style="height: 720px; width: 100%; margin-top: 5px" :suppressDragLeaveHidesColumns="true"
        rowSelection="multiple" @grid-ready="apsGridReady" :defaultColDef="defaultColDef" class="ag-theme-alpine"
        :rowData="pageData.apsList" :columnDefs="aspTableColumns" :localeText="localeText1"
        :suppressMovableColumns="true">
      </AgGridVuesCopys>
    </div>
  </a-drawer>
</template>

<script lang='ts' setup>
import { reactive, toRefs, ref, onMounted } from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import { post, get } from '@/api/http'
import { FormInstance, Message, Modal } from '@arco-design/web-vue'

import { localeText } from '@/api/aggridZw'
import { pagingList } from '@/api/paging'
import { color } from 'echarts'
import ReturnGoodsOutVue from '@/views/wh/ReturnGoodsOut.vue'
import { CellRangeType } from 'ag-grid-community'
import { invalid } from 'moment'
import { Post } from '@/api/basedata'

const pagingList1: any = ref(pagingList)
const localeText1: any = ref(localeText)
const pageData: any = reactive({
  apsShow: false,
  equipmentShow: false,
  sideTitle: '',
  rHeight: 0,
  arrangedList: [],
  unscheduledList: [],
  flowList: [],
  apsList: [],
  timeList: [],
  equipmentList: [],
  pageLoading: false,
  pageLoading2: false,
  arrangedSum: '',
  onePlace: '',
  twoPlace: '',
  unscheduledSum: '',
  equipment: '',
  working: '',
  free: '',
  workshopId: null,
  workshopId2: null,
  flowCardCode: '',
  flowCardCode2: '',
  machineList: [],
  machineTypeId: null,
  machineTypeId2: null,
  typeList: [],
})

const dataForm: any = reactive({
  flowCardCode: '',
  castNum: '',
  houseNum: '',
  flowCardWeight: '',
  cylinderType: '',
  machineCodes: [],
  workshopId: null,
})

const defaultColDef: any = {
  sortable: true,
  resizable: true,
  filter: true,
}

// 未排产表格
const gridOption = ref()
const gridReady = (params: any) => {
  gridOption.value = params.api
}
let tableColumns: any = [
  { headerName: '管型', field: 'castNum', width: 100 },
  { headerName: '工序', field: 'processName', width: 100 },
  { headerName: '流转状态', field: 'cardState', width: 100 },
  {
    headerName: '色样',
    field: 'colorSample',
    width: 100,
    cellRenderer: {
      template: ` <a-image v-if="val.colorSample" :src="val.colorSample" /> 
                    <span v-if="!val.colorSample"></span>`,
      setup(props: any) {
        const val = ref(props.params.data)
        return {
          val,
        }
      },
    },
  },
  { headerName: '色称', field: 'colorName', width: 100 },
  { headerName: '流转卡号', field: 'flowCardCode', width: 100 },
  { headerName: '匹数', field: 'houseNum', width: 100 },
  { headerName: '重量(KG)', field: 'flowCardWeight', width: 100 },
  { headerName: '色号', field: 'colorCode', width: 100 },
  { headerName: '客户', field: 'customName', width: 100 },
  { headerName: '品牌', field: 'dd', width: 100 },
  { headerName: '布名', field: 'clothCode', width: 100 },
  { headerName: '衫款', field: 'dd', width: 100 },
  { headerName: '订单类型', field: 'dd', width: 100 },
  { headerName: '流转卡类型', field: 'dd', width: 100 },
  {
    headerName: 'HOLD单状态',
    field: 'holdState',
    width: 100,
    cellRenderer: {
      template: `<div>{{ val.holdState == 0 ? '否' : '是' }}</div>`,
      setup(props: any) {
        let val = ref(props.params.data)
        return {
          val,
        }
      },
    },
    filterParams: {
      valueFormatter: function (params: any) {
        return params.value == 0 ? '否' : params.value == 1 ? '是' : ''
      },
    },
  },
  { headerName: '交期', field: 'deliveryTime', width: 100 },
  { headerName: '计划开始', field: 'dd', width: 100 },
  { headerName: '计划结束', field: 'dd', width: 100 },
  { headerName: '备注', field: 'remark', width: 100 },
  {
    headerName: '工艺流程',
    //工序动态表头
    children: [],
  },
  {
    headerName: '操作',
    field: 'action',
    width: 100,
    pinned: 'right',
    cellRenderer: {
      template: `<a-button type="primary" size="mini" @click="c">排产</a-button>`,
      setup(props: any) {
        const c = () => {
          apsMethod(props.params.data)
        }
        return {
          c,
        }
      },
    },
  },
]

// 已排产表格
const gridOption2 = ref()
const gridReady2 = (params: any) => {
  gridOption2.value = params.api
}
let tableColumns2: any = [
  {
    field: '',
    pinned: 'left',
    rowDrag: (params: any) => {
      return !(params.data.machineOrder == null)
    },
    width: 50,
  },
  { headerName: '管型', field: 'castNum', width: 100 },
  { headerName: '工序', field: 'processName', width: 100 },
  { headerName: '车间', field: 'workshop', width: 100 },
  { headerName: '机台号', field: 'machineCode', width: 100 },
  { headerName: '排位', field: 'machineOrder', width: 100 },
  {
    headerName: '色样',
    field: 'colorSample',
    width: 100,
    cellRenderer: {
      template: ` <a-image v-if="val.colorSample" :src="val.colorSample" /> 
                    <span v-if="!val.colorSample"></span>`,
      setup(props: any) {
        const val = ref(props.params.data)
        return {
          val,
        }
      },
    },
  },
  { headerName: '色称', field: 'colorName', width: 100 },
  { headerName: '流转卡号', field: 'flowCardCode', width: 100 },
  { headerName: '匹数', field: 'houseNum', width: 100 },
  { headerName: '重量(KG)', field: 'flowCardWeight', width: 100 },
  { headerName: '色号', field: 'colorCode', width: 100 },
  { headerName: '客户', field: 'customName', width: 100 },
  { headerName: '品牌', field: 'dd', width: 100 },
  { headerName: '布名', field: 'clothCode', width: 100 },
  { headerName: '衫款', field: 'dd', width: 100 },
  { headerName: '流转卡类型', field: 'dd', width: 100 },
  {
    headerName: 'HOLD单状态',
    field: 'holdState',
    width: 100,
    cellRenderer: {
      template: `<div>{{ val.holdState == 0 ? '否' : '是' }}</div>`,
      setup(props: any) {
        let val = ref(props.params.data)
        return {
          val,
        }
      },
    },
    filterParams: {
      valueFormatter: function (params: any) {
        return params.value == 0 ? '否' : params.value == 1 ? '是' : ''
      },
    },
  },
  { headerName: '交期', field: 'deliveryTime', width: 100 },
  { headerName: '计划开始', field: 'dd', width: 100 },
  { headerName: '计划结束', field: 'dd', width: 100 },
  { headerName: '备注', field: 'remark', width: 100 },
  { headerName: '工艺流程', children: [] },
  {
    headerName: '操作',
    field: 'action',
    width: 100,
    pinned: 'right',
    cellRenderer: {
      template: `<a-button type="primary" size="mini" @click="c">进度跟踪</a-button>`,
      setup(props: any) {
        const c = () => {
          // editTurntable(props.params.data)
        }
        return {
          c,
        }
      },
    },
  },
]

//机台排产表格
const apsGridOption = ref()
const apsGridReady = (params: any) => {
  apsGridOption.value = params.api
}
const aspTableColumns: any = ref([])

//未排区 查询
const formRef: any = ref()
function doRefresh() {
  formRef.value?.validate().then((err: any) => {
    if (!err) {
      pageData.pageLoading = true
      get({
        url: 'aps/workSequenceTask/findTaskByMachinTypeAndStatus',
        data: {
          status: 0,
          workshopId: pageData.workshopId ? pageData.workshopId : 0,
          flowCardCode: pageData.flowCardCode,
          machineTypeId: pageData.machineTypeId,
        },
      })
        .then(({ data, code }: any) => {
          if (code === 200) {
            columnsName(tableColumns, data)
            tableColumns = [...tableColumns]
            pageData.unscheduledList = data
            pageData.unscheduledSum = pageData.unscheduledList.length
            pageData.equipment = '染色机'
            gridOption.value.setRowData(data)
          }
        })
        .catch(console.log)
        .finally(() => {
          pageData.pageLoading = false
        })
    }
  })
}

//已排区 查询
const formRef2 = ref()
function doRefresh2(code: any) {
  formRef2.value?.validate().then((err: any) => {
    if (!err) {
      pageData.pageLoading2 = true
      get({
        url: 'aps/workSequenceTask/findTaskByMachinTypeAndStatus',
        data: {
          status: 1,
          workshopId: pageData.workshopId2 ? pageData.workshopId2 : 0,
          flowCardCode: pageData.flowCardCode2,
          machineTypeId: pageData.machineTypeId2,
          machineCode: code ? code : null,
        },
      })
        .then(({ data, code }: any) => {
          if (code === 200) {
            columnsName(tableColumns2, data)
            tableColumns2 = [...tableColumns2]
            pageData.arrangedList = data
            pageData.arrangedSum = pageData.arrangedList.length
            pageData.onePlace = pageData.arrangedList.filter((o: any) => o.machineOrder == 1).length
            pageData.twoPlace = pageData.arrangedList.filter((o: any) => o.machineOrder == 2).length
            gridOption2.value.setRowData(data)
          }
        })
        .catch(console.log)
        .finally(() => {
          pageData.pageLoading2 = false
        })
    }
  })
}

// 自定义的单元格渲染器
const customCellRenderer = (params: any) => {
  const flowList = params.data.flowList
  const isExists = flowList && flowList.includes(params.colDef.headerName)
  return isExists ? 'Y' : 'N'
}

// 定义样式函数
const customCellStyle = (params: any) => {
  const flowList = params.data.flowList
  const isExists = flowList && flowList.includes(params.colDef.headerName)
  return isExists ? { backgroundColor: '#64dd3f' } : { backgroundColor: '#b7b3b3' }
}

//工艺流程动态获取子表头数据
const columnsName = (columns: any, data: any) => {
  const childColumns = columns.find((col: any) => col.headerName === '工艺流程')
  if (data.length > 0) {
    childColumns.children = data[0].processNames.map((name: any) => ({
      headerName: name,
      field: '',
      width: 100,
      cellRenderer: customCellRenderer,
      cellStyle: customCellStyle,
    }))
  } else {
    delete childColumns.children
  }
}

//排产 弹窗
const apsMethod = (val: any) => {
  dataForm.flowCardCode = val.flowCardCode + '_' + val.taskId
  dataForm.castNum = val.castNum
  dataForm.houseNum = val.houseNum
  dataForm.flowCardWeight = val.flowCardWeight
  dataForm.cylinderType = val.cylinderType
  pageData.sideTitle = '车间任务发布'
  if (!pageData.workshopId) {
    Message.warning('请先选择车间')
    return
  }
  if (!pageData.machineTypeId) {
    Message.warning('请先选择机台类型')
    return
  }
  workshopTask(pageData.workshopId, pageData.machineTypeId)
}

//已排产修改 弹窗
const editOrder = () => {
  dataForm.flowCardCode = ''
  dataForm.castNum = ''
  pageData.sideTitle = '已排产顺序调整'
  if (!pageData.machineTypeId2) {
    Message.warning('请先选择机台类型')
    return
  }
  workshopTask(pageData.workshopId2, pageData.machineTypeId2)
}

//车间任务发布  已排产顺序调整
const workshopTask = (workshopId: any, machineTypeId: any) => {
  pageData.sideTitle == '车间任务发布'
    ? (pageData.pageLoading = true)
    : (pageData.pageLoading2 = true)
  let url =
    pageData.sideTitle == '车间任务发布'
      ? 'aps/workSequenceTask/findTaskSequenceForScheduling'
      : 'aps/workSequenceTask/findMachineTaskSequence'
  get({
    url: url,
    data: {
      workshopId: workshopId ? workshopId : 0,
      castNum: '',
      machineTypeId: machineTypeId,
    },
  }).then(({ code, data, message }) => {
    if (code == 200) {
      dataForm.machineCodes = data.machineCodes
      // 推荐机台 赋值
      let foundEmpty = false
      data.flowCardMachineMap.forEach((o: any) => {
        if (!foundEmpty && !o[data.recommendMachineCode]) {
          o[data.recommendMachineCode] = dataForm.flowCardCode
          foundEmpty = true
          //新增一行空白数据 可拖拽
          const newlist = {}
          data.machineCodes.forEach((code: any) => {
            newlist[code] = ''
          })
          data.flowCardMachineMap.push(newlist)
        }
      })
      //如果推荐机台无位置，新增加一行数据push
      if (!foundEmpty) {
        const newObject = {}
        data.machineCodes.forEach((code: any) => {
          newObject[code] = ''
        })
        newObject[data.recommendMachineCode] = dataForm.flowCardCode
        data.flowCardMachineMap.push(newObject)
      }
      pageData.apsList = data.flowCardMachineMap

      //拖拽方法
      aspTableColumns.value = []
      const topLevelHeaders = Object.keys(data.machineCodeMap)
      topLevelHeaders.forEach((topHeader) => {
        const subHeaders = data.machineCodeMap[topHeader]
        // 动态多表头
        aspTableColumns.value.unshift({
          headerName: topHeader,
          children: subHeaders.map((res: any) => ({
            headerName: res,
            field: res,
            minWidth: 39,
            width: 100,
            wrapHeaderText: true,
            autoHeaderHeight: true,
            cellStyle: (val: any) => {
              if (pageData.sideTitle != '已排产顺序调整' && val.value == dataForm.flowCardCode) {
                return { backgroundColor: 'skyblue' } //推荐机台底色为蓝色
              }
              return null // 保持原样
            },
            cellRenderer: {
              template: `<div style="width:100px;height:32px;text-align:center;" draggable="true" @dragstart="onDragStart"
                             @dragover="allowDrop" @drop="drop">{{ params.data[val] ? params.data[val].split('_')[0] : '' }}
                         </div>`,
              setup(props: any) {
                const val = ref(res)
                let isRecommendedMachine: any =
                  props.params.data[val.value] == dataForm.flowCardCode // 检查是否是推荐机台列
                //根据条件 是否允许拖拽
                const onDragStart = (event: any) => {
                  if (
                    props.params.data[val.value] &&
                    isRecommendedMachine &&
                    pageData.sideTitle != '已排产顺序调整'
                  ) {
                    event.dataTransfer.setData(
                      'text/col/row',
                      JSON.stringify({
                        text: props.params.data[val.value],
                        col: val.value,
                        row: props.params.rowIndex,
                      })
                    )
                  } else if (
                    props.params.data[val.value] &&
                    pageData.sideTitle == '已排产顺序调整'
                  ) {
                    event.dataTransfer.setData(
                      'text/col/row',
                      JSON.stringify({
                        text: props.params.data[val.value],
                        col: val.value,
                        row: props.params.rowIndex,
                      })
                    )
                  } else {
                    event.preventDefault()
                  }
                }
                // 是否允许放置拖拽的任务
                const allowDrop = (event: any) => {
                  event.preventDefault()
                }
                // 放置任务时调用 获取拖拽的数据并处理
                const drop = (event: any) => {
                  event.preventDefault()
                  const droppedData = JSON.parse(event.dataTransfer.getData('text/col/row'))
                  if (droppedData.col === val.value) {
                    let oldCol = data.flowCardMachineMap.map((o: any) => o[droppedData.col])
                    let oldLine = droppedData.row
                    let desLine = props.params.rowIndex
                    let arr = oldCol.splice(oldLine, 1)
                    oldCol.splice(desLine, 0, arr[0])
                    data.flowCardMachineMap.forEach((o: any, index: number) => {
                      o[val.value] = oldCol[index]
                    })
                  } else {
                    let fromCol = data.flowCardMachineMap.map((o: any) => o[droppedData.col]) //原队列
                    let toCol = data.flowCardMachineMap.map((o: any) => o[val.value]) //新队列
                    let fromLine = droppedData.row //原行
                    let desLine = props.params.rowIndex //目标行
                    let arr = fromCol.splice(fromLine, 1) //删除原行拖动值
                    toCol.splice(desLine, 0, arr[0]) //添加
                    if (toCol[toCol.length - 1]) {  //最后一行数据时自动增加一行
                      const newObject = {}
                      data.machineCodes.forEach((code: any) => {
                        newObject[code] = ''
                      })
                      newObject[data.recommendMachineCode] = dataForm.flowCardCode
                      data.flowCardMachineMap.push(newObject)
                    }

                    data.flowCardMachineMap.forEach((o: any, index: number) => {
                      o[val.value] = toCol[index]
                      o[droppedData.col] = fromCol[index]
                    })
                  }
                  pageData.apsList = data.flowCardMachineMap.filter((row: any) => {
                    return Object.values(row).some((value) => value)  //清除空行
                  })
                }
                return {
                  val,
                  drop,
                  allowDrop,
                  onDragStart,
                  isRecommendedMachine,
                }
              },
            },
          })),
        })
      })
      pageData.apsShow = true
      pageData.pageLoading = false
      pageData.pageLoading2 = false
    } else {
      Message.error(message)
    }
  })
}
const apsOk = () => {
  //判断机台中队列是否排满 中间不能有空格
  let invalid = false
  dataForm.machineCodes.forEach((code: any) => {
    let firstPosi = -1
    let resList: any = [...pageData.apsList].reverse()
    resList.forEach((o: any, i: any) => {
      if (firstPosi == -1) {
        if (o[code]) {
          firstPosi = i
        }
      } else {
        if (!o[code]) {
          invalid = true
          return
        }
      }
    })
  })
  if (invalid) {
    Message.warning('机台队列中间未排满！')
    return
  }

  //保存
  pageData.pageLoading = true
  post({
    url: 'aps/workSequenceTask/updateTaskWithMachineCode',
    data: pageData.apsList.filter((row: any) => {
      return Object.values(row).some((value) => value !== '') // 检查每个属性是否都为空
    }),
  }).then(({ code, message }) => {
    if (code == 200) {
      Message.success('成功')
      pageData.apsShow = false
      pageData.pageLoading = false
      doRefresh()
      doRefresh2(machineCode)
    } else {
      Message.error(message)
    }
  })
}

// 定义调换位置的方法
const transferDown = () => {
  const alreadyOrdered2: any = document.getElementById('alreadyOrdered2')
  const notOrdered2: any = document.getElementById('notOrdered2')
  const gang2: any = document.getElementById('gang2')
  // 获取两个元素的父级节点
  const parent = alreadyOrdered2.parentNode
  // 获取两个元素在父级节点中的位置索引
  const indexA = Array.from(parent.children).indexOf(alreadyOrdered2)
  const indexB = Array.from(parent.children).indexOf(notOrdered2)
  // 将notOrdered2插入到alreadyOrdered2之前
  parent.insertBefore(notOrdered2, alreadyOrdered2)
  // 将alreadyOrdered2插入到notOrdered2原来的位置
  if (indexA < indexB) {
    // 如果alreadyOrdered2原来在gang2之前，插入到gang2之前
    parent.insertBefore(alreadyOrdered2, gang2.nextSibling)
  } else {
    // 如果alreadyOrdered2原来在gang2之后，插入到gang2之后
    parent.insertBefore(alreadyOrdered2, gang2)
  }
}

// 顺序调整
const onRowDragEnd = (params: any) => {
  const { overIndex, node } = params
  const draggedRowData = node.data
  const currentIndex = pageData.arrangedList.indexOf(draggedRowData)
  pageData.arrangedList.splice(currentIndex, 1)
  pageData.arrangedList.splice(overIndex, 0, draggedRowData)
  //查找拖动行相同的machineCode
  const draggedMachineCode = draggedRowData.machineCode
  const sameMachineGroup = pageData.arrangedList.filter(
    (item: any) => item.machineCode === draggedMachineCode
  )
  sameMachineGroup.forEach((o: any, index: number) => {
    o.machineOrder = index + 1
  })
  //更新数组
  pageData.arrangedList = [...pageData.arrangedList]
  let list = pageData.arrangedList.filter((o: any) => o.machineCode == draggedMachineCode)
  let data: any = []
  list.forEach((o: any) => {
    let newData = { id: o.taskId, machineOrder: o.machineOrder }
    data.push(newData)
  })
  //实时更新顺序
  post({
    url: 'aps/workSequenceTask/updateTaskMachineOrder',
    data: data,
  }).then((res: any) => {
    if (res.code === 200) {
      doRefresh2(machineCode)
    } else {
      Message.error(res.message)
    }
  })
}

// 更新颜色
let machineCode: any = ''
const machineQuery = (index: any, code: any) => {
  machineCode = code
  doRefresh2(code)
  pageData.machineList.forEach((item: any, i: any) => {
    if (i == index) {
      item.backColor = '#05de66'
      item.shadowColor = '1px 6px 2px #11ba5b'
    } else {
      item.backColor = 'rgb(175, 175, 175)'
      item.shadowColor = '1px 6px 2px #a1a1a1'
    }
  })
}

//机台类型下拉
const machineTypeSearch = () => {
  post({
    url: 'aps/dwMachineType/getMachineTypePage',
    data: {
      page: 1,
      size: 100000,
    },
  }).then((res: any) => {
    if (res.code === 200) {
      pageData.typeList = res.data.list.filter((o: any) => o.typeName != '染布机')
    }
  })
}

//机台查询
const machineSearch = () => {
  get({
    url: 'aps/workSequenceTask/findMachineTaskSequence',
    data: {
      workshopId: pageData.workshopId2 ? pageData.workshopId2 : 0,
      castNum: '',
      machineTypeId: pageData.machineTypeId2,
    },
  }).then((res: any) => {
    if (res.code === 200) {
      pageData.machineList = res.data.machineCodes.map((o: any) => {
        return { code: o }
      })
    }
  })
}

onMounted(() => {
  pageData.rHeight = document.getElementsByClassName('main-section')[0]?.clientHeight
  //弹出层的高
  if (pageData.rHeight !== undefined) {
    pageData.rHeight = pageData.rHeight
  }
  machineTypeSearch()
  // Query()
})
</script>
<style lang='less' scoped>
:deep(.ag-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
  user-select: initial;
  -moz-user-select: text;
  -ms-user-select: text;
  -webkit-user-select: text;
}

:deep(.arco-table-td-content) {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

#gang2 {
  height: 20px;
  margin-top: 20px;
  margin-bottom: 20px;
  background-color: #f0f2f5;
}

.divInterval {
  border: 2px solid #f0f2f5;
  width: 100%;
  height: 2px;
  margin-top: 10px;
  margin-bottom: 12px;
}

.buttonLeft {
  width: 0px;
  height: 400px;
  color: #fff;
}

.divCenter {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.divMachine {
  display: inline-block;
  margin-left: 17px;
  width: 60px;
  height: 30px;
  box-sizing: border-box;
  background-color: rgb(175, 175, 175);
  box-shadow: 1px 6px 2px #a1a1a1;
  transition: all 0.5s;
  text-align: center;
  line-height: 30px;
  border-radius: 5px;
  color: black;
  font-weight: bold;
  cursor: pointer;
  margin-top: 20px;
}

.divMachine:hover {
  background-color: #05de66;
  box-shadow: 1px 6px 2px #11ba5b;
}

.divMachine:hover .divMachine-text {
  transform: rotateX(5deg);
}

.divMachine.active {
  background-color: #11767e;
  box-shadow: 0 4px 0 #243c47;
  transform: translateY(4px);
  /* active时下移，按钮被按下的效果 */
}

:deep(.custom-header-class) {
  background-color: #fff !important;

  &:hover {
    background-color: #fff !important;
  }
}

.table {
  th {
    border: 1px solid #babfc7;
    text-align: center;
    padding: 8px;
  }
}
</style>